<template>
  <div class="ele-body">
    <div style="display: flex; justify-content: space-between">
      <three-school :activeList="activeList" load-school @click="schoolChange" @visible="threeSchoolVisible=$event"></three-school>
      <el-card shadow="never" style="width: 100%">
        <div :style="threeSchoolVisible ? '' : 'padding-left: 16px'">
          <b style="margin-bottom:4px; display: inline-block;">学校名称：{{ query.schoole_name || "暂无学校" }}</b>
          <el-form
              inline size="mini"
              :model="query"
              class="ele-form-search"
              @keyup.enter.native="reload"
              @submit.native.prevent
          >
            <el-form-item label="性别:">
              <el-select
                  style="width: 100%"
                  clearable
                  v-model="query.sex"
                  placeholder="请选择性别"
              >
                <el-option value="0" label="女"/>
                <el-option value="1" label="男"/>
                <el-option value="2" label="保密"/>
              </el-select>
            </el-form-item>
            <el-form-item label="" label-width="0">
              <el-input
                  placeholder="请输入姓名或账户名称，联系方式"
                  v-model="query.keyword"
                  style="width: 100%"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                  type="primary"
                  icon="el-icon-search"
                  class="ele-btn-icon"
                  @click="reload"
              >查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="toolbar-box" style="margin-bottom: 4px">
          <div class="tool-btn">
            <el-button
                @click="showImport = true"
                icon="el-icon-upload2"
                class="ele-btn-icon"
                size="mini"
            >导入
            </el-button>
            <el-button
                size="mini"
                type="default"
                icon="el-icon-download"
                class="ele-btn-icon"
                @click="exportExcel"
            >导出
            </el-button>
          </div>
          <div class="tool-tab">
            <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                class="ele-btn-icon"
                :disabled="!selection.length"
                @click="removeBatch"
            >删除
            </el-button>
            <el-button
                size="mini"
                type="primary"
                icon="el-icon-plus"
                class="ele-btn-icon"
                @click="openEdit(null)"
            >添加
            </el-button>
          </div>
        </div>
        <!-- 数据表格 -->
        <el-table
            border
            lazy
            ref="table"
            :data="data"
            v-loading="loading"
            height="calc(100vh - 315px)"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center">
          </el-table-column>
          <el-table-column
              label="序号"
              width="55"
              align="center"
              type="index"
          >
            <template slot-scope="scope">
                <span
                    v-text="$setTableIndex(query.page, query.limit, scope.$index)"
                >
                </span>
            </template>
          </el-table-column>
          <el-table-column label="老师ID" align="center" prop="id"></el-table-column>
          <el-table-column label="头像" align="center" prop="avatar">
            <template slot-scope="scope">
              <img
                  v-lazy="scope.row.avatar?$api+scope.row.avatar:imgAvatar"
                  style="width: 50px; height: 50px"
              />
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center" prop="realname"/>
          <el-table-column label="账户名称" align="center" prop="username"/>
          <el-table-column label="角色" align="center" prop="role_id">
            <template slot-scope="scope">
              {{ fun_list(scope.row.role_id, roleList) }}
            </template>
          </el-table-column>
          <el-table-column label="联系方式" align="center" prop="mobile"/>
          <el-table-column label="所属学校" align="center">
            <template>
              <span>{{ query.schoole_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center" prop="sex">
            <template slot-scope="scope">
              {{ scope.row.sex === 0 ? '未知' : scope.row.sex === 1 ? '男' : scope.row.sex === 2 ? '女' : '' }}
            </template>
          </el-table-column>
          <el-table-column
              label="创建时间"
              align="center"
              prop="create_time"
              width="200"
          >
            <template slot-scope="scope">{{
                scope.row.create_time
                    ? $util.toDateString(scope.row.create_time)
                    : "暂无"
              }}
            </template>
          </el-table-column>
          <el-table-column
              label="操作"
              align="center"
              fixed="right"
              width="200"
              :resizable="true"
          >
            <template slot-scope="{ row }">
              <el-link
                  type="text"
                  :underline="false"
                  icon="el-icon-edit"
                  @click="openEdit(row)"
              >修改
              </el-link>
              <el-popconfirm
                  class="ele-action"
                  title="确定要删除该老师吗？"
                  @confirm="remove(row)"
              >
                <el-link
                    type="text"
                    slot="reference"
                    :underline="false"
                    icon="el-icon-delete"
                >删除
                </el-link>
              </el-popconfirm>
              <el-link
                  type="text"
                  :underline="false"
                  icon="el-icon-edit"
                  @click="
                    obj_xgMima.id = row.id;
                    obj_xgMima.username = row.username;
                    obj_xgMimaShow = true;
                  "
              >修改密码
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            :total="total"
            :page.sync="query.page"
            :limit.sync="query.limit"
            @pagination="getData"
        />
      </el-card>
    </div>
    <!-- 编辑弹窗 -->
    <indexList-edit
        :id="query.schoole_id"
        :name="query.schoole_name"
        :data="current"
        :visible.sync="showEdit"
        @done="reload"
    />
    <!-- 导入弹窗-->
    <importFile :schooleId="query.schoole_id" :visible.sync="showImport" @done="reload"/>

    <el-dialog title="修改密码" :visible.sync="obj_xgMimaShow">
      <el-form ref="form_pwd" :model="obj_xgMima" :rules="rules_pwd">
        <el-form-item label="账号">
          <el-input
              clearable
              :disabled="true"
              :maxlength="20"
              v-model="obj_xgMima.username"
              placeholder="请输入老师名称"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              clearable
              :maxlength="12"
              type="password"
              v-model="obj_xgMima.password"
              placeholder="请输入新密码"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="obj_xgMimaShow = false">取 消</el-button>
        <el-button type="primary" @click="obj_xgMima_fn">确定修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import indexListEdit from "./indexList-edit.vue";
import regions from "ele-admin/packages/regions";
import threeSchool from "@/components/three_schoole.vue";
import importFile from "./importFile";
import imgAvatar from '@/assets/avatar.jpg'

export default {
  components: {indexListEdit, threeSchool, importFile},
  computed: {
    ...mapGetters(["permission"]),
  },
  data() {
    return {
      threeSchoolVisible: true,
      //imgAvatar: require("@/assets/avatar.jpg"),
      imgAvatar,
      // 省市区数据
      regions: regions,
      row_span: 20,
      // 选中的省市区
      city: [],
      loading: false, // 表格加载状态
      selection: [], // 表格选中数据
      total: 0, // 数据总数
      data: [], // 表格数据接口
      roleList: [],
      obj_xgMimaShow: false,
      obj_xgMima: {
        id: "",
        password: "",
        username: "",
      },
      rules_pwd: {
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          // {type: 'string',pattern: /^[a-zA-Z0-9]{6,12}$/,message:'密码长度应在6-12位之间，并且只能包含字母和数字',trigger: ['blur','change']},
          {
            validator: (rule, value, callback) => {
              // 检查长度是否在6-12位之间
              if (!/^[a-zA-Z0-9]{6,12}$/.test(value)) {
                callback(new Error("密码长度应在6-12位之间，并且只能包含字母和数字"));
              } else {
                // 检查是否包含至少一个数字
                const hasNumber = /\d/.test(value);
                // 检查是否包含至少一个字母
                const hasLetter = /[a-zA-Z]/.test(value);

                if (!hasNumber || !hasLetter) {
                  callback(new Error("密码必须包含至少一个数字和至少一个字母"));
                } else {
                  callback(); // 验证通过
                }
              }
            },
            trigger: ["blur", "change"]
          }
        ],
      },
      // 表格搜索条件
      query: {
        page: 1,
        limit: 20,
        sex: "",
        keyword: "",
        schoole_id: "",
        schoole_name: "",
      },
      streetsList: [],
      schoolList: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      // 是否显示导入弹窗
      showImport: false,
      schoolListData: [],
      activeList: []
    };
  },
  mounted() {
    this.$http
        .get("/role/getRoleList")
        .then((res) => {
          if (res.data.code === 0) {
            this.roleList = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    this.$http
        .get("/schoole/index", {
          params: {
            page: 1,
            limit: 1,
          },
        })
        .then((res) => {
          if (res.data.count == 0) return;
          this.query = {
            page: 1,
            limit: 20,
            sex: "",
            keyword: "",
            schoole_id: res.data.data[0].id,
            schoole_name: res.data.data[0].title,
          };
          this.activeList = [
            res.data.data[0].province_code,
            res.data.data[0].city_code,
            res.data.data[0].district_code,
            res.data.data[0].streets_code,
          ];
          this.getData();
        })
        .catch((e) => {
          this.loading = false;
          this.$message.error(e.message);
        });
  },
  watch: {},
  methods: {
    obj_xgMima_fn() {
      this.$refs["form_pwd"].validate((valid) => {
        if (valid) {
          this.$http
              .post("/teacher/edit", {
                ...this.obj_xgMima,
                schoole_id: this.query.schoole_id,
              })
              .then(() => {
                this.$message.success("修改成功");
                this.obj_xgMimaShow = false;
              })
              .catch(() => {
                this.obj_xgMimaShow = false;
              });
        }
      })
    },
    fun_list(id, list) {
      return list.find((e) => e.id == id)?.name;
    },
    schoolChange(data) {
      this.query = {
        page: 1,
        limit: 20,
        sex: "",
        keyword: "",
        schoole_id: data.value,
        schoole_name: data.label,
      };
      this.getData();
    },
    /* 导出数据Excel */
    exportExcel() {
      let info = JSON.parse(JSON.stringify(this.query));
      console.log(info)
      this.$http
          .get("/teacher/exportExcel", {params: {...info, export_type: 0}})
          .then((res) => {
            let data = res.data;
            if (data.code == 0) {
              // 下载文件
              window.location.href = data.data;
              this.$message({
                type: "success",
                message: "导出成功",
              });
            } else {
              this.$message.error("导出失败");
            }
          })
    },
    /* 获取表格数据 */
    getData() {
      this.loading = true;
      this.$http
          .get("/teacher/index", {params: this.query})
          .then((res) => {
            this.loading = false;
            this.total = res.data.count;
            this.data = res.data.data;
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
    },
    /* 查询数据 */
    reload() {
      this.getData();
    },
    /* 重置搜索 */
    reset() {
      this.query.sex = "";
      this.query.keyword = "";
      this.reload();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
    },
    /* 显示编辑 */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },
    /* 删除 */
    remove(row) {
      const loading = this.$loading({lock: true});
      this.$http
          .post(`/teacher/delete`, {id: row.id})
          .then((res) => {
            loading.close();
            if (res.data.code === 0) {
              this.$message.success(res.data.msg);
              this.reload();
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.message);
          });
    },
    /* 批量删除 */
    removeBatch() {
      if (!this.selection.length) {
        this.$message.error("请至少选择一条数据");
        return;
      }
      this.$confirm("确定要删除选中的老师吗?", "提示", {
        type: "warning",
      })
          .then(() => {
            const loading = this.$loading({lock: true});
            this.$http
                .post("/teacher/delete", {id: this.selection.map((d) => d.id)})
                .then((res) => {
                  loading.close();
                  if (res.data.code === 0) {
                    this.$message({type: "success", message: res.data.msg});
                    this.reload();
                  } else {
                    this.$message.error(res.data.msg);
                  }
                })
                .catch((e) => {
                  loading.close();
                  this.$message.error(e.message);
                });
          })
          .catch(() => {
          });
    },
  },
};
</script>

<style scoped>
.toolbar-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.right_show {
  position: absolute;
  left: -15px;
  top: 2px;
  display: inline-block;
  text-align: center;
  line-height: 30px;
  background-color: #1890ff;
  border-top-right-radius: 50%;
  border-bottom-right-radius: 50%;
  width: 30px;
  color: #fff;
  cursor: pointer;
}
</style>
